<script>
  import L from 'leaflet';
  import { isEmpty, cloneDeep, orderBy, assign } from 'lodash';
  import 'istrong-leaflet-windmarker';
  import { WGS84ToGCJ02 } from 'istrong-map-coordinate-transformation';
  import vgMap from '../../components/Map.vue';
  import Position from '../../libs/leaflet-positionmarker';

  let sortByField, sortByOrders;
  let sortByFieldFunc = (data) => {
    let ls = orderBy(data, sortByField, sortByOrders);
    return ls;
  };
  let wind_dir_enum = {
    A: 0,
    B: 22.5,
    C: 45,
    D: 67.5,
    E: 90,
    F: 112.5,
    G: 135,
    H: 180,
    I: 202.5,
    J: 225,
    K: 247.5,
    L: 270,
    M: 292.5,
    N: 315,
    O: 337.5,
    P: 360
  }

  export default {
    name: 'windMap',
    components: {
      'vg-map': vgMap
    },
    props: {
      beginTime: {
        type: String,
        required: true
      },
      endTime: {
        type: String,
        required: true
      },
      data: {
        type: Array,
        default: []
      },
      positionMarker: {
        type: String,
        default: ''
      },
      collisionZoom: {
        type: Number
      }
    },
    data() {
      return {
        crs: 'EPSG3857',
        zoom: 8,
        center: [26, 119],
        baseLayers: [],
        thematicLayers: [],
        zoomControl: {},
        layersControl: {},
        vStationLayerName: 'vWindStation',//矢量站点名称
        vStationMarkers: {}
      }
    },
    watch: {
      data: function (val) {
        this._loadVStationsToMap();
      },
      positionMarker: function (val) {
        this._startPosition();
      }
    },
    mounted() {
      this._loadVStationsToMap();

      this._startPosition();
    },
    methods: {
      _loadVStationsToMap() {
        let coConfig = this.$AppConfig.module.wind.mapPage ? this.$AppConfig.module.wind.mapPage.collision || {} : {};
        let vMap = this.$refs.map;
        vMap.clearLayer(this.vStationLayerName);
        if (!this.data || this.data.length === 0) {
          return;
        }
        let layerOpts = assign({
          latlngBounds: L.latLngBounds([-20, 60], [60, 200]),
          map: vMap.Map,
          sortByField: sortByFieldFunc
        }, this._collisionOpts);
        this.vStationMarkers = {};
        vMap.addCollisionLayer(this.vStationLayerName, layerOpts, this.data, this._vStationsMarkerInit)
      },
      _vStationsMarkerInit(stationInfo, layer) {
        stationInfo.lat = stationInfo.lat || stationInfo.latitude;
        stationInfo.lng = stationInfo.lng || stationInfo.longitude;
        if (!stationInfo.lat || !stationInfo.lng) {
          return;
        }
        let vector = this.vStationMarkers;
        // let gcj02 = WGS84ToGCJ02({ lng: stationInfo.lng, lat: stationInfo.lat });
        let latlng = L.latLng(stationInfo.lat, stationInfo.lng);
        stationInfo.id = stationInfo.id || stationInfo._id;
        if (vector[stationInfo.id]) {
          // layer.removeLayer(vector[stationInfo.id]);
          return;
        }

        let marker = new L.WindCanvasMarker(latlng,
          {
            direction: wind_dir_enum[stationInfo.wind_dir],
            power: stationInfo.wind_power,
            speed: stationInfo.wind_speed,
            size: [14, 27],
            radius: 10,
            minZoom: stationInfo.min_zoom || 6,
            feature: stationInfo,
            collision: (this.collisionZoom === undefined || stationInfo.min_zoom > this.collisionZoom),
            zoomtobridle: true,
            renderer: this.$refs.map.RenderCanvas
          });
        marker.on('click', this._showChartInfo, this);

        let toolTip = (new L.TooltipAutoDirection({//(new L.Tooltip({
          permanent: false,
          sticky: false,
          interactive: true,
          mapPreclickToClose: false,
          minZoom: stationInfo.min_zoom || 6,
          className: 'windTooltip',
          feature: stationInfo
        }, marker)).setContent(stationInfo.name + (stationInfo.wind_power !== undefined ? ' ' + stationInfo.wind_power + '(级) ' + stationInfo.wind_speed + '(m/s)' + ' ' + stationInfo.wind_dir_desc : ''));
        toolTip.on('click', this._showChartInfo, this);
        marker.bindTooltip(toolTip);

        vector[stationInfo.id] = marker;
        return marker;
      },
      _showChartInfo(e) {
        let feature = e.target.options.feature;
        this.$emit('showChartInfo', feature);
      },
      onChangeShowType() {
        this.$emit('changeShowType', 'list');
      },
      onOpenFilterPanel() {
        this.$emit('setFilterConditions', true);
      },
      _startPosition() {
        if (this.positionMarker === '') {
          return;
        }
        Position.startPosition(this, this.$refs.map.Map, this.positionMarker, this.vStationMarkers, 13);
        this.$emit('positionEnd');
      }
    },
    created() {
      let mapConfig = this.$AppConfig.map;
      this.crs = mapConfig.crs;
      this.zoom = mapConfig.zoom;
      this.center = mapConfig.center;
      this.baseLayers = cloneDeep(mapConfig.baseLayers);
      this.thematicLayers = cloneDeep(mapConfig.thematicLayers);
      this.zoomControl = mapConfig.zoomControl;
      this.layersControl = mapConfig.layersControl;

      let moduleWind = mapConfig.module ? mapConfig.module.wind : null;
      if (moduleWind) {
        let baseLayer = moduleWind.baseLayer;
        if (baseLayer) {
          this.baseLayers.forEach(item => {
            item.checked = (item.id === baseLayer ||
              item.name === baseLayer);
          });
        }
        this.zoom = moduleWind.zoom || this.zoom;
        this.center = moduleWind.center || this.center;
        let thematicLayers = [];
        this.thematicLayers.forEach(item => {
          if (moduleWind.thematicLayers[item.id + '']) {
            thematicLayers.push(assign(item, moduleWind.thematicLayers[item.id + '']));
          }
        });
        this.thematicLayers = thematicLayers;
      }

      let {mapPage} = this.$AppConfig.module.wind;
      let collision = mapPage.collision || {};
      if (collision.sortBy) {
        sortByField = [];
        sortByOrders = collision.sortBy.orders || ['desc'];
        collision.sortBy.field.forEach(item => {
          sortByField.push(function (o, a) {
            return o.options.feature[item];
          });
        });
      } else {
        sortByFieldFunc = 'wind_speed';
      }
      this._collisionOpts = {
        onlyCollisionTooltip: collision.onlyCollisionTooltip !== undefined ? collision.onlyCollisionTooltip : true,
        markerOffset: collision.markerOffset || [1, 1],
        tooltipOffset: collision.tooltipOffset || [0, 0],
      };
      if (collision.latlngBounds && collision.latlngBounds.length > 0) {
        this._collisionOpts.latlngBounds = L.latLngBounds(
          [collision.latlngBounds[0], collision.latlngBounds[1]],
          [collision.latlngBounds[2], collision.latlngBounds[3]]);
      }
    },
    beforeDestroy() {
    }
  }
</script>
<template>
  <div id="mapViewer">
    <vg-map :crs="crs" :baseLayers="baseLayers" :thematicLayers="thematicLayers" :zoom="zoom" :center="center" :zoomControl="zoomControl"
      :layersControl="layersControl" ref="map"></vg-map>
    <div class="mapViewer-TopRight-Controls">
      <div class="btChangeRouterList" @click="onChangeShowType">
        <span class="ion-ios-list"></span>
      </div>
      <div class="mapViewer-ButtonFilter" @click="onOpenFilterPanel">
        <img src="../../assets/filter.png" />
      </div>
    </div>
  </div>
</template>
<style>

.windTooltip{
  background: rgba(255, 255, 255, 0.7)!important;
}
</style>